package com.googlecode.gendevcode.maven.service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.googlecode.gendevcode.common.Cache;
import com.googlecode.gendevcode.common.Util;
import com.googlecode.gendevcode.common.VelocityFactory;
import com.googlecode.gendevcode.maven.MvnConstants;
import com.googlecode.gendevcode.model.ProjectXml;
import com.googlecode.gendevcode.model.pdm.ColumnPdmXml;
import com.googlecode.gendevcode.model.pdm.TablePdmXml;
import com.googlecode.gendevcode.model.pdm.ViewPdmXml;
import com.googlecode.gendevcode.service.basic.GenCodeFilesServiceSupport;

/**
 * 生成代码文件实现类(Maven)
 * @author devilishking
 *
 */
public class MvnGenCodeFilesServiceImpl extends GenCodeFilesServiceSupport {
	/**
	 * 创建代码文件  
	 * @param tablePdmXmlList 待生成的表信息列表
	 * @param viewMap	                视图集合<视图编号, 视图信息>
	 * @param genLevel 	                项目生成级别
	 * @param projectXml      项目信息
	 * @throws Exception
	 */
	public void genCodeFilesXml(List<TablePdmXml> tablePdmXmlList, Map<String, ViewPdmXml> viewMap, String genLevel, ProjectXml projectXml) throws Exception{
		if (MvnConstants.GENLEVEL_COLUMN.equals(genLevel)){
			for(TablePdmXml tablePdmXml : tablePdmXmlList){
				StringBuilder xmlData = new StringBuilder().append("<columns>\r\n");
				ViewPdmXml viewPdmXml = viewMap.get(tablePdmXml.getViewId());
				String[] packageCode = viewPdmXml.getPackageCode().split("\\.");
				String module = packageCode[packageCode.length-1];
				String className = (new StringBuilder()).append(tablePdmXml.getClassName().substring(0, 1).toLowerCase())
														.append(tablePdmXml.getClassName().substring(1))
														.toString();
				String resourceTxnCode = (new StringBuilder()).append(module.toUpperCase()).append("_")
						   									  .append(className.substring(module.length()).toUpperCase())
						   									  .toString();
				List<ColumnPdmXml> columnPdmXmlList = tablePdmXml.getColumnPdmXmlList();
				boolean isFirst = true;
				xmlData.append("	<!-- ").append(tablePdmXml.getName()).append(" ")
					   				   .append(tablePdmXml.getCode())
					   				   .append(" [start] -->\r\n");
				for(int i = 0; i < columnPdmXmlList.size(); i++){
					ColumnPdmXml columnPdmXml = columnPdmXmlList.get(i);
					String columnId = columnPdmXml.getCode();
					String columnLength = columnPdmXml.getLength() != null && columnPdmXml.getLength().trim().length() > 0 ? 
											columnPdmXml.getLength().toString() : "";
					String dataType = columnPdmXml.getDataType().toLowerCase();
					String isQuickSearch = "0";
					String isSearch = "0";
					String allowBlank = columnPdmXml.getMandatory() ? "0" : "1";
					String isHide = "0";
					String code = "";
					if ("integer".equals(dataType) || "long".equals(dataType)){
						dataType = "int";
					}
					if ("timestamp".equals(dataType)){
						dataType = "date";
					}
					if (isFirst && columnId.toLowerCase().indexOf("id") < 0 && "string".equals(dataType)){
						isQuickSearch = "1";
						isFirst = false;
					}
					if (columnId.toLowerCase().indexOf("id") < 0 
							&& !"createUser".equals(columnId)
							&& !"createTime".equals(columnId)
							&& !"modUser".equals(columnId)
							&& !"modTime".equals(columnId)
							&& !"remark".equals(columnId)
							&& !"delFlag".equals(columnId)
							&& !"byzd1".equals(columnId)
							&& !"byzd2".equals(columnId)
							&& !"byzd3".equals(columnId)){
						if ("string".equals(dataType) || "int".equals(dataType)
													  || "double".equals(dataType)
													  || "date".equals(dataType)){
							isSearch = "1";
						}
					}
					else{
						if(!"remark".equals(columnId)) isHide = "1";
					}
					if (columnPdmXml.getDictionary() != null && columnPdmXml.getDictionary().trim().length() > 0){
						code = (new StringBuffer()).append(module.toUpperCase())
												   .append("_")
												   .append(tablePdmXml.getClassName().toUpperCase())
												   .append("_")
												   .append(columnPdmXml.getCode().toUpperCase())
												   .toString();
					}
					xmlData.append("	<column>\r\n")
						   .append("		<resourceTxnCode>").append(resourceTxnCode).append("</resourceTxnCode>\r\n")
						   .append("		<columnId>").append(columnId).append("</columnId>\r\n")
						   .append("		<columnName>").append(columnPdmXml.getName()).append("</columnName>\r\n")
						   .append("		<columnType>").append(dataType).append("</columnType>\r\n")
						   .append("		<columnLength>").append(columnLength).append("</columnLength>\r\n")
						   .append("		<columnMaxLength>").append(columnLength).append("</columnMaxLength>\r\n")
						   .append("		<isQuickSearch>").append(isQuickSearch).append("</isQuickSearch>\r\n")
						   .append("		<isSearch>").append(isSearch).append("</isSearch>\r\n")
						   .append("		<searchKey></searchKey>\r\n")
						   .append("		<searchName></searchName>\r\n")
						   .append("		<allowBlank>").append(allowBlank).append("</allowBlank>\r\n")
						   .append("		<isForm>1</isForm>\r\n")
						   .append("		<isHide>").append(isHide).append("</isHide>\r\n")
						   .append("		<flex></flex>\r\n")
						   .append("		<height></height>\r\n")
						   .append("		<code>").append(code).append("</code>\r\n")
						   .append("		<groupIndex></groupIndex>\r\n")
						   .append("		<sortNo>").append(i+1).append("</sortNo>\r\n")
						   .append("		<tabIndex>0</tabIndex>\r\n")
						   .append("	</column>\r\n");
				}
				xmlData.append("	<!-- ")
			       	   .append(tablePdmXml.getName()).append(" ")
			       	   .append(tablePdmXml.getCode())
			       	   .append(" [end] -->\r\n");
				xmlData.append("</columns>");			
				if (xmlData.length() > 0){
					Util.writeFile(xmlData.toString(), 
								   (new StringBuilder()).append(projectXml.getResourcesPath())
								   					    .append("/createColumn_")
								   					    .append(tablePdmXml.getCode()).append("_")
								   					    .append(String.valueOf(System.currentTimeMillis()))
								   					    .append(".xml")
								   					    .toString());
				}
			}
		}
		else{
			super.genCodeFilesXml(tablePdmXmlList, viewMap, genLevel, projectXml);			
		}
	}
	
	/**
	 * 创建页面文件
	 * @param dataMap     页面所属数据
	 * @param tablePdmXml 表信息
	 * @param viewPdmXml  视图信息
	 * @param projectXml  项目信息
	 * @param 
	 * @throws Exception
	 */
	public void genPagesFile(Map<String, Object> dataMap, TablePdmXml tablePdmXml, ViewPdmXml viewPdmXml, ProjectXml projectXml) throws Exception{
		if(tablePdmXml.getClassName()==null){
			throw new Exception("表对应的实体类名未定义！ \n" + tablePdmXml) ;
		}
		String[] packageCode = viewPdmXml.getPackageCode().split("\\.");
		String module = packageCode[packageCode.length-1];
		String className = (new StringBuilder()).append(tablePdmXml.getClassName().substring(0, 1).toLowerCase())
												.append(tablePdmXml.getClassName().substring(1))
												.toString();
		String genFilePath = (new StringBuilder()).append(projectXml.getProjectPath())
												  .append("/").append(projectXml.getName()).append("-web")
												  .append("/").append(MvnConstants.BASE_PAGEPATH)
												  .append("/").append(module)
												  .append("/").append(className)
												  .toString();
		File file = new File((new StringBuilder()).append(genFilePath).append("/").toString());
		if (!file.exists()) file.mkdirs();

		if (tablePdmXml.getName().indexOf('表') == tablePdmXml.getName().length()-1){
			tablePdmXml.setName(tablePdmXml.getName().substring(0, tablePdmXml.getName().length()-1));
		}
		
		String vmFileUrl = "maven/page_js.vm";
		String[] treeColumnCodes = new String[]{ "code", "parentId", "depth" };
		int markTreeSign = 0;
		boolean isStatus = false;
		boolean isSort = false;
		String pkCoumnCode = "";
		List<ColumnPdmXml> columnPdmXmlList = tablePdmXml.getColumnPdmXmlList();
		List<ColumnPdmXml> dictionaryList = new ArrayList<ColumnPdmXml>();
		for(ColumnPdmXml columnPdmXml : columnPdmXmlList){
			if (markTreeSign < treeColumnCodes.length){
				for(String treeColumnCode : treeColumnCodes){
					if (treeColumnCode.equals(columnPdmXml.getCode())) markTreeSign++;
					if (markTreeSign >= treeColumnCodes.length) break;
				}
			}
			if (columnPdmXml.getDictionary() != null && columnPdmXml.getDictionary().trim().length() > 0){
				if ("status".equals(columnPdmXml.getCode())){
					isStatus = true;
				}
				dictionaryList.add(columnPdmXml);
			}
			if ("sortNo".equals(columnPdmXml.getCode())) isSort = true;
			if (columnPdmXml.getIsPK()) pkCoumnCode = columnPdmXml.getCode();
		}
		if (markTreeSign == treeColumnCodes.length){
			boolean isTree = inputBoolean(String.format("[%0$s]是否需要生成树页面? (false: 否; true: 是) : true: ", tablePdmXml.getCode()), true);
			System.out.println();
			if (isTree){ 
				vmFileUrl = "maven/page_js_for_tree.vm";
				isSort = true;
			}
		}
		
		dataMap.put("tablePdmXml", tablePdmXml);
		dataMap.put("pkCoumnCode", pkCoumnCode);
		dataMap.put("dictionaryList", dictionaryList);
		dataMap.put("isSort", isSort);
		dataMap.put("isStatus", isStatus);
		dataMap.put("txnCodePrefix", (new StringBuilder()).append(module.toUpperCase())
														  .append("_").append(className.substring(module.length()).toUpperCase())
														  .toString());
		dataMap.put("module", module);
		dataMap.put("className", className);
		VelocityFactory.writeFile(dataMap, "maven/page_jsp.vm", 
								  (new StringBuffer()).append(genFilePath)
								  					  .append("/").append(className)
								  					  .append(".jsp").toString(), 
								  Cache.getInstance().getRootPath());		
		
		VelocityFactory.writeFile(dataMap, vmFileUrl, 
								  (new StringBuffer()).append(genFilePath)
								  					  .append("/").append(className)
								  					  .append(".js").toString(), 
								  Cache.getInstance().getRootPath());
	}
}
